package com.happyhome.services;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.happyhome.constants.AppConstant;
import com.happyhome.constants.ComTxManagerName;
import com.happyhome.dao.OpinionDao;
import com.happyhome.datamodel.Opinion;

@Service
public class OpinionServiceImpl implements OpinionService{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(OpinionServiceImpl.class);
	
	@Autowired
    private OpinionDao opinionDao;

	@Override
	public List<Opinion> getAllOpinions() {
		return opinionDao.getAllOpinions();
	}

	@Override
	public List<Opinion> getListOpinionsIsDisplay() {
		return opinionDao.getListOpinionsIsDisplay();
	}

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public Opinion merge(Opinion opinion) {
		return opinionDao.merge(opinion);
	}

	@Override
	public Opinion findById(Long id) {
		return opinionDao.find(id);
	}

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public void setDisplayCavas(List<Long> listId) {
		List<Opinion> listOpinionInList = opinionDao.getListOpinionsInListId(listId);
		for(Opinion newsIn : listOpinionInList){
			newsIn.setIsDisplay(Boolean.valueOf("true"));
		}
		
		List<Opinion> listOpinionsOutList = opinionDao.getListOpinionsNotInListId(listId);
		for(Opinion newsOut : listOpinionsOutList){
			newsOut.setIsDisplay(Boolean.valueOf("false"));
		}
		opinionDao.flush();
	}

	@Override
	public List<Opinion> getOpinionDisplay() {
		List<Opinion> opinions = null;
		opinions = opinionDao.getListOpinionIsDisplay();
		if(opinions == null){
			opinions = opinionDao.getListOpinionNewest(AppConstant.LIMIT_CAVAS_OPINION);
		}
		if(opinions != null){
			for(Opinion opinion : opinions){
				if(opinion.getImage() != null){
					opinion.setUrl("/" + AppConstant.APP_URL + "/picture/" + opinion.getImage().getId());
				}
			}
		}
		return opinions;
	}
}
